package net.bplaced.streetfighter.fragment;

import net.bplaced.streetfighter.GuestbookActivity;
import net.bplaced.streetfighter.R;
import net.bplaced.streetfighter.lib.async.task.CommentPostTask;
import net.bplaced.streetfighter.lib.model.Comment;
import net.bplaced.streetfighter.lib.utils.CallBack;
import net.bplaced.streetfighter.lib.utils.RuntimeData;
import net.bplaced.streetfighter.lib.utils.RuntimeDataKey;
import net.bplaced.streetfighter.lib.utils.ServiceReturnPackage;
import net.bplaced.streetfighter.lib.utils.StreetfighterUtils;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * @author Sebastian Hoffmann <bo.hoffi@googlemail.com>
 */
public class ReplyFragment
        extends Fragment {

    private RelativeLayout view = null;

    private Comment commentToReplyTo;
    private Comment reply;

    private EditText authorName;
    private EditText commentEntry;

    private boolean isValid = true;
    private boolean isTablet;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        this.view = (RelativeLayout) inflater.inflate(R.layout.view_reply, container, false);

        this.prepareView();

        if (RuntimeData.getInstance().get(RuntimeDataKey.IS_TABLET) != null) {
            this.isTablet = (Boolean) RuntimeData.getInstance().get(RuntimeDataKey.IS_TABLET).getData();
        }

        return this.view;
    }

    private void prepareView() {

        this.commentToReplyTo = (Comment) RuntimeData.getInstance().get(RuntimeDataKey.COMMENT).getData();

        this.authorName = (EditText) this.view.findViewById(R.id.reply_to_comment_name);
        this.commentEntry = (EditText) this.view.findViewById(R.id.reply_to_comment_text);

        // Läd den gespeicherten Usernamen, sonst leer
        this.authorName.setText(StreetfighterUtils.getPreferenceString(this.getActivity(), this.getActivity()
                .getResources().getString(R.string.const_pref_key_reply_user), ""));

        final Button postCommentBtn = (Button) this.view.findViewById(R.id.reply_to_comment_post);
        postCommentBtn.setOnClickListener(this.postCommentListener);
    }

    /**
     * Deklariert einen Callback, welcher zum Ende des Serviceaurufes aufgerufen wird.
     */
    private final CallBack<ServiceReturnPackage<String>> onFinishedLoading =
            new CallBack<ServiceReturnPackage<String>>() {

                @Override
                public void callbackAction(ServiceReturnPackage<String> result) {

                    if (result != null) {
                        if (result.getErrorMessage() != null) {

                            Toast.makeText(ReplyFragment.this.getActivity(), result.getErrorMessage(),
                                    Toast.LENGTH_SHORT).show();

                        } else {

                            StreetfighterUtils.changeContent(ReplyFragment.this.getFragmentManager(),
                                    ReplyFragment.this.getActivity(), ReplyFragment.this.isTablet,
                                    R.id.main_detail_container, new ReplyFragment(),
                                    new Intent(ReplyFragment.this.getActivity(), GuestbookActivity.class));

                        }
                    }
                };
            };

    private final View.OnClickListener postCommentListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            ReplyFragment.this.isValid = true;

            if (ReplyFragment.this.authorName.getText().length() == 0) {
                ReplyFragment.this.isValid = false;
                ReplyFragment.this.authorName.setError(ReplyFragment.this.getResources().getString(
                        R.string.reply_to_comment_duty_text_name));
            }

            if (ReplyFragment.this.commentEntry.getText().length() == 0) {
                ReplyFragment.this.isValid = false;
                ReplyFragment.this.commentEntry.setError(ReplyFragment.this.getResources().getString(
                        R.string.reply_to_comment_duty_text_entry));
            }

            if (ReplyFragment.this.isValid) {

                ReplyFragment.this.reply = new Comment();
                ReplyFragment.this.reply.author = ReplyFragment.this.authorName.getText().toString();
                ReplyFragment.this.reply.authorEmail = "";
                ReplyFragment.this.reply.authorUrl = "";
                ReplyFragment.this.reply.authorIp = "192.1.1.128";
                ReplyFragment.this.reply.commentText = ReplyFragment.this.commentEntry.getText().toString();
                ReplyFragment.this.reply.parentComment = ReplyFragment.this.commentToReplyTo.id;

                ReplyFragment.this.checkSavedUserName();
            }
        }
    };

    private void postComment() {

        final CommentPostTask task =
                new CommentPostTask(this.getActivity(), this.getResources().getString(
                        R.string.reply_to_comment_progress_message), this.onFinishedLoading);
        task.execute(this.reply.author, "", "", this.reply.authorIp, this.reply.commentText,
                this.reply.parentComment.toString());
    }

    private void checkSavedUserName() {

        final String enteredUserName = this.authorName.getText().toString();
        final String savedUserName =
                StreetfighterUtils.getPreferenceString(this.getActivity(),
                        this.getActivity().getResources().getString(R.string.const_pref_key_reply_user), "");

        if (!enteredUserName.equals(savedUserName)) {

            this.saveUserName(enteredUserName);

        } else {
            this.postComment();
        }
    }

    private void saveUserName(final String userName) {

        final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
        builder.setTitle(R.string.reply_to_comment_dialog_title)
                .setMessage(R.string.reply_to_comment_dialog_message)
                .setPositiveButton(R.string.reply_to_comment_dialog_positive_button,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                StreetfighterUtils.setPreferenceString(
                                        ReplyFragment.this.getActivity(),
                                        ReplyFragment.this.getActivity().getResources()
                                                .getString(R.string.const_pref_key_reply_user), userName);

                                ReplyFragment.this.postComment();
                            }
                        })
                .setNegativeButton(R.string.reply_to_comment_dialog_negative_button,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                ReplyFragment.this.postComment();
                            }
                        }).create().show();
    }
}